from flask import jsonify, request, Response
from supermarket.app import app, db, redis_store
from supermarket.app.models import Product
import csv
from io import StringIO


# 商品管理的CRUD操作
@app.route('/products', methods=['GET'])
def get_products():
    try:
        products = Product.query.all()
        serialized_products = [product.to_dict() for product in products]
        return jsonify(serialized_products), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/products/<int:id>', methods=['GET'])
def get_product(id):
    try:
        product = Product.query.get_or_404(id)
        serialized_product = product.to_dict()
        return jsonify(serialized_product), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/products', methods=['POST'])
def create_product():
    try:
        data = request.get_json()
        new_product = Product(**data)
        db.session.add(new_product)
        db.session.commit()
        return jsonify(new_product.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/products/<int:id>', methods=['PUT'])
def update_product(id):
    try:
        product = Product.query.get_or_404(id)
        data = request.get_json()
        for key, value in data.items():
            setattr(product, key, value)
        db.session.commit()
        return jsonify(product.to_dict()), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/products/<int:id>', methods=['DELETE'])
def delete_product(id):
    try:
        product = Product.query.get_or_404(id)
        db.session.delete(product)
        db.session.commit()
        return jsonify({'message': 'Product deleted'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


# 导出CSV
@app.route('/products/export/csv', methods=['GET'])
def export_products_csv():
    try:
        products = Product.query.all()
        output = StringIO()
        writer = csv.writer(output)
        # 写入CSV头部
        writer.writerow(['id', 'name', 'price', 'supplier_id', 'description', 'remark'])
        # 写入CSV行
        for product in products:
            writer.writerow([product.id, product.name, product.price, product.supplier_id, product.description,
                             product.remark])
        output.seek(0)
        return Response(output, mimetype='text/csv', headers={'Content-Disposition': 'attachment; filename=products.csv'}),200
    except Exception as e:
        return jsonify({'error': str(e)}), 400
